package cn.mumzone.pos.ui.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.display.DisplayManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.AppCompatImageView;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ruffian.library.widget.RLinearLayout;
import com.ruffian.library.widget.RTextView;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnLongClick;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.netstatus.NetChangeObserver;
import cn.mumzone.basic.netstatus.NetStateReceiver;
import cn.mumzone.basic.netstatus.NetUtils;
import cn.mumzone.basic.util.DeviceIdUtils;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.event.MoreViewChangeEvent;
import cn.mumzone.pos.event.NetConnectedEvent;
import cn.mumzone.pos.model.AppVersionEntity;
import cn.mumzone.pos.model.BannerEntity;
import cn.mumzone.pos.presenter.HomePresenter;
import cn.mumzone.pos.presenter.contract.HomeContract;
import cn.mumzone.pos.ui.fragment.FRA_BusinessReportForms;
import cn.mumzone.pos.ui.fragment.FRA_CashGoods;
import cn.mumzone.pos.ui.fragment.FRA_CashService;
import cn.mumzone.pos.ui.fragment.FRA_StockCheck;
import cn.mumzone.pos.ui.fragment.FRA_More;
import cn.mumzone.pos.ui.fragment.FRA_OffWorkRecord;
import cn.mumzone.pos.ui.fragment.FRA_SaleCard;
import cn.mumzone.pos.ui.fragment.FRA_Schedule;
import cn.mumzone.pos.ui.fragment.FRA_StockIn;
import cn.mumzone.pos.ui.fragment.FRA_StockOut;
import cn.mumzone.pos.ui.fragment.FRA_StockSearch;
import cn.mumzone.pos.ui.fragment.bills.FRA_Bill;
import cn.mumzone.pos.ui.fragment.inventory.FRA_Inventory;
import cn.mumzone.pos.ui.fragment.member.FRA_Member;
import cn.mumzone.pos.ui.fragment.warehouse.FRA_OutWarehouse;
import cn.mumzone.pos.ui.fragment.warehouse.FRA_Warehouse;
import cn.mumzone.pos.ui.widgets.DifferentDisplay;
import cn.mumzone.pos.ui.widgets.RocketProgressView;
import cn.mumzone.pos.util.AppUtil;
import cn.mumzone.pos.util.UpdateAppService;
import cn.mumzone.pos.util.print.PrinterService;
import cn.mumzone.pos.ui.fragment.FRA_ServerTimeTable;

/**
 * Created by JoeLjt on 2019/6/13.
 * Email: lijiateng1219@gmail.com
 * Description:
 */

public class ACT_Home extends BaseActivity<HomePresenter> implements HomeContract.View {

    public static int OVERLAY_PERMISSION_REQ_CODE = 101;


    @BindView(R.id.iv_cash)
    AppCompatImageView ivCashService;

    @BindView(R.id.iv_reserve)
    AppCompatImageView ivReserve;

    @BindView(R.id.iv_member)
    AppCompatImageView ivMember;

    @BindView(R.id.iv_bill)
    AppCompatImageView ivBill;

    @BindView(R.id.iv_sale_card)
    AppCompatImageView ivSaleCard;

    @BindView(R.id.iv_help)
    AppCompatImageView ivHelp;

    @BindView(R.id.iv_more)
    AppCompatImageView ivMore;

    @BindView(R.id.ll_cash)
    LinearLayout llCashService;

    @BindView(R.id.ll_cash_goods)
    LinearLayout llCashGoods;

    @BindView(R.id.iv_cash_goods)
    AppCompatImageView ivCashGoods;

    @BindView(R.id.ll_reserve)
    LinearLayout llReserve;

    @BindView(R.id.ll_member)
    LinearLayout llMember;

    @BindView(R.id.ll_bill)
    LinearLayout llBill;

    @BindView(R.id.ll_sale_card)
    LinearLayout llSaleCard;

    @BindView(R.id.ll_help)
    LinearLayout llHelp;

    @BindView(R.id.ll_more)
    LinearLayout llMore;

    private ImageView mPreImageView;
    private LinearLayout mPreLinearLayout;

    private Fragment mDefaultFragment;
    private Fragment mCurrFragment;

    private FRA_CashService mFraCashService;
    private FRA_Member mFraMember;
    private FRA_SaleCard mSaleCard;
    private FRA_More mFraMore;
    private FRA_Schedule mFraSchedule;
    private FRA_ServerTimeTable mFraReserve;
    private FRA_BusinessReportForms mFraForms;
    private FRA_StockSearch mFraSearchRepository;
    private FRA_StockCheck mFraCheckStock;
    private FRA_StockOut mFraStockOut;
    private FRA_StockIn mFraStockIn;
    private FRA_OffWorkRecord mFraOffWorkRecord;

    private FRA_Warehouse mInWarehouse;
    private FRA_OutWarehouse mOutWarehouse;
    private FRA_Inventory mInventory;

        private FRA_Bill mFraBill;
//    private FRA_Inventory mFraBill;

    private FRA_CashGoods mFraGoods;


    private DifferentDisplay mPresentation;
    private List<BannerEntity> banners;

    private boolean hasSecondLevelFragment = false;
    private Fragment currentSecondLevelFragment;
    private RocketProgressView rocketProgressView;

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected void initEventAndData() {

        mFraMember = new FRA_Member();
        mFraBill = new FRA_Bill();
//        mFraBill = new FRA_Inventory();
        mFraMore = new FRA_More();
        mFraForms = new FRA_BusinessReportForms();
        mFraSearchRepository = new FRA_StockSearch();
        mFraCheckStock = new FRA_StockCheck();
        mFraStockOut = new FRA_StockOut();
        mFraStockIn = new FRA_StockIn();
        mFraOffWorkRecord = new FRA_OffWorkRecord();

        mInWarehouse = new FRA_Warehouse();
        mOutWarehouse = new FRA_OutWarehouse();
        mInventory = new FRA_Inventory();

        if (AppUtil.isOnlyHasGoodsBusiness()) {
            mFraGoods = new FRA_CashGoods();
            mDefaultFragment = mFraGoods;

            llCashGoods.setVisibility(View.VISIBLE);
            llCashService.setVisibility(View.GONE);
            llReserve.setVisibility(View.GONE);
            llSaleCard.setVisibility(View.GONE);


        } else {
            mFraCashService = new FRA_CashService();
            mFraReserve = new FRA_ServerTimeTable();
            mSaleCard = new FRA_SaleCard();
            mFraSchedule = new FRA_Schedule();
            mDefaultFragment = mFraCashService;

            llCashGoods.setVisibility(View.GONE);
            llCashService.setVisibility(View.VISIBLE);
            llReserve.setVisibility(View.VISIBLE);
            llSaleCard.setVisibility(View.VISIBLE);


        }

        if (!mDefaultFragment.isAdded()) {
            mCurrFragment = mDefaultFragment;
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.fl_container, mDefaultFragment);
            transaction.commitAllowingStateLoss();
        }

        if (AppUtil.isOnlyHasGoodsBusiness()) {
            updateCheckStatus(llCashGoods, ivCashGoods);

        } else {
            updateCheckStatus(llCashService, ivCashService);
        }


        initPresentation();

        mPresenter.checkAppUpdate();
        mPresenter.initEvents();
        mPresenter.setDownloadingListener();
        mPresenter.getMemberLevel();


        startService(new Intent(this, PrinterService.class));
        NetStateReceiver.registerNetworkStateReceiver(this);

        NetStateReceiver.registerObserver(new NetChangeObserver() {
            @Override
            public void onNetConnected(NetUtils.NetType type) {
                Elog.e("TAG----", "wifi已连接");
                if (type == NetUtils.NetType.WIFI) {
                    RxBus.getDefault().post(new NetConnectedEvent());
                }
            }

            @Override
            public void onNetDisConnect() {
                Elog.e("TAG----", "wifi已断开");
                super.onNetDisConnect();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetStateReceiver.unRegisterNetworkStateReceiver(this);
    }

    //交班页面跳转监听
    @Override
    public void showMoreViewChanged(int type) {
        switch (type) {
            case MoreViewChangeEvent.MORE_VIE_HOME:
                switchContent(mCurrFragment, mFraMore);
                hasSecondLevelFragment = false;
                break;
            case MoreViewChangeEvent.MORE_VIE_OFF_WORK:
                switchContent(mCurrFragment, mFraOffWorkRecord);
                currentSecondLevelFragment = mFraOffWorkRecord;
                hasSecondLevelFragment = true;
                break;
            case MoreViewChangeEvent.MORE_VIE_SCHEDULE:
                switchContent(mCurrFragment, mFraSchedule);
                currentSecondLevelFragment = mFraSchedule;
                hasSecondLevelFragment = true;
                break;
            case MoreViewChangeEvent.MORE_VIE_REPORT:
                switchContent(mCurrFragment, mFraForms);
                currentSecondLevelFragment = mFraForms;
                hasSecondLevelFragment = true;
                break;
            case MoreViewChangeEvent.MORE_VIE_REPOSITORY:
                switchContent(mCurrFragment, mFraSearchRepository);
                currentSecondLevelFragment = mFraSearchRepository;
                hasSecondLevelFragment = true;
                break;
            case MoreViewChangeEvent.MORE_VIEW_CHECK_STOCK:
                switchContent(mCurrFragment, mFraCheckStock);
                currentSecondLevelFragment = mFraCheckStock;
                hasSecondLevelFragment = true;
                break;
            case MoreViewChangeEvent.MORE_VIEW_STOCK_OUT:
                switchContent(mCurrFragment, mFraStockOut);
                currentSecondLevelFragment = mFraStockOut;
                hasSecondLevelFragment = true;
                break;
            case MoreViewChangeEvent.MORE_VIEW_STOCK_IN:
                switchContent(mCurrFragment, mFraStockIn);
                currentSecondLevelFragment = mFraStockIn;
                hasSecondLevelFragment = true;
                break;
            case MoreViewChangeEvent.MORE_VIEW_IN_WAREHOUSE: //入库单列表页面切换
                switchContent(mCurrFragment, mInWarehouse);
                currentSecondLevelFragment = mInWarehouse;
                hasSecondLevelFragment = true;
                break;
            case MoreViewChangeEvent.MORE_VIEW_OUT_WAREHOUSE: //出库单列表页面切换
                switchContent(mCurrFragment, mOutWarehouse);
                currentSecondLevelFragment = mOutWarehouse;
                hasSecondLevelFragment = true;
                break;
            case MoreViewChangeEvent.MORE_VIEW_INVENTROY: //盘点单列表页面切换
                switchContent(mCurrFragment, mInventory);
                currentSecondLevelFragment = mInventory;
                hasSecondLevelFragment = true;
                break;
        }
    }

    /**
     * 设置更新进度条
     *
     * @param progress 进度
     */
    @Override
    public void onDownloadingProgress(int progress) {
        if (rocketProgressView != null) {
            rocketProgressView.setPercent(progress / 100f);
        }
    }


    private void initPresentation() {

        DisplayManager mDisplayManager = (DisplayManager) this.getSystemService(Context.DISPLAY_SERVICE);
        Display[] displays = mDisplayManager.getDisplays();
        if (displays.length > 1) {
            mPresentation = new DifferentDisplay(getApplicationContext(), displays[1]);// displays[1]是副屏
            mPresentation.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

            mPresenter.requestBannerList();
        }
    }

    @Override
    public void onBackPressed() {
        if (hasSecondLevelFragment) {
            RxBus.getDefault().post(new MoreViewChangeEvent(MoreViewChangeEvent.MORE_VIE_HOME));
            return;
        }
        super.onBackPressed();
    }

    private void updateCheckStatus(LinearLayout linearLayout, ImageView imageView) {

        if (mPreLinearLayout == linearLayout) {
            return;
        }

        linearLayout.setBackgroundColor(Color.parseColor("#59595C"));
        imageView.setColorFilter(Color.WHITE);

        if (mPreLinearLayout != null && mPreImageView != null) {
            mPreLinearLayout.setBackgroundColor(Color.TRANSPARENT);
            mPreImageView.setColorFilter(Color.parseColor("#7e7e7e"));
        }

        mPreLinearLayout = linearLayout;
        mPreImageView = imageView;

        Fragment toFragment = null;
        switch (linearLayout.getId()) {
            case R.id.ll_cash_goods:
                toFragment = mFraGoods;
                break;
            case R.id.ll_cash:
                toFragment = mFraCashService;
                break;
            case R.id.ll_reserve:
                toFragment = mFraReserve;
                break;
            case R.id.ll_member:
                toFragment = mFraMember;
                break;
            case R.id.ll_bill:
                toFragment = mFraBill;
                break;
            case R.id.ll_sale_card:
                toFragment = mSaleCard;
                break;
            case R.id.ll_more:
                if (hasSecondLevelFragment) {
                    toFragment = currentSecondLevelFragment;
                } else {
                    toFragment = mFraMore;
                }
                break;
        }
        switchContent(mCurrFragment, toFragment);
    }

    public void switchContent(Fragment from, Fragment to) {
        if (null != to && mCurrFragment != to) {

            mCurrFragment = to;
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(from).add(R.id.fl_container, to).commitAllowingStateLoss(); // 隐藏当前的fragment，add
                // 下一个到Activity中
            } else {
                transaction.hide(from).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }

            if (from instanceof BaseFragment && ((BaseFragment) from).hasPopupHint()
                    && ((BaseFragment) from).isPopupHintPrepared()) {
                ((BaseFragment) from).hidePopupHint();
            }

            if (to instanceof BaseFragment && ((BaseFragment) to).hasPopupHint()
                    && ((BaseFragment) to).isPopupHintPrepared()) {
                ((BaseFragment) to).showPopupHint();
            }

        }
    }

    @Override
    protected int getLayout() {
        return R.layout.act_home;
    }

    @OnClick({R.id.ll_cash_goods, R.id.ll_cash, R.id.ll_reserve, R.id.ll_member, R.id.ll_bill, R.id.ll_sale_card, R.id.ll_more,
            R.id.ll_help, R.id.ll_setting, R.id.iv_logo})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_cash_goods:
                updateCheckStatus(llCashGoods, ivCashGoods);
                break;
            case R.id.ll_cash:
                updateCheckStatus(llCashService, ivCashService);
                break;
            case R.id.ll_reserve:
                updateCheckStatus(llReserve, ivReserve);
                break;
            case R.id.ll_member:
                updateCheckStatus(llMember, ivMember);
                break;
            case R.id.ll_bill:
                updateCheckStatus(llBill, ivBill);
                break;
            case R.id.ll_sale_card:
                updateCheckStatus(llSaleCard, ivSaleCard);
                break;
            case R.id.ll_help:
                ACT_HelpCenter.startAct(this);
                break;
            case R.id.ll_more:
                updateCheckStatus(llMore, ivMore);
                break;
            case R.id.ll_setting:
                ACT_Setting.startAc(mContext);
                break;
            case R.id.iv_logo:
                mPresenter.onClickCount();
                break;

        }
    }

    @OnLongClick({R.id.iv_logo})
    public boolean onViewLongClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_logo:
                mPresenter.onClickLong();
                break;
        }
        return true;
    }

    @Override
    public void onDebugModeOpened() {
        PosToast.INSTANCE.makeToast(mContext, PosToast.ToastType.TOAST_TYPE_SQUARE,
                PosToast.ToastSquareLevel.ALERT_FAIL_SQUARE, "已进入debug模式", false);
    }

    public static void startAc(Context context) {
        Intent intent = new Intent(context, ACT_Home.class);
        context.startActivity(intent);
    }

    @Override
    public void showCheckAppUpdate(AppVersionEntity result) {

        String nowVersion = DeviceIdUtils.getLocalVersionName(mContext);
        String version = "";
        if (AppUtil.isAppSunMiVersion()) {
            version = result.getPosSmVersion();
        } else {
            version = result.getPosVersion();
        }
        mPresenter.doSaveVersion(version);
        if (!nowVersion.equals(version)) {

            initUpdateDialog(result.getUpdateInfo(), version, result.isForceUpd());
//            mUpdateAppDialog.show();
//            mUpdateProgressDialog.setCanceledOnTouchOutside(!result.isForceUpd());
//            tvCancelUpdate.setVisibility(result.isForceUpd() ? View.GONE : View.VISIBLE);
        } else {

//            if (!nowVersion.equals(mSp.getString(AppConstants.VERION_NAME, ""))) {
//                showVersionDialog();
//                mSp.putString(AppConstants.VERION_NAME, nowVersion);
//            }
        }
    }

    @Override
    public void showBannerList(List<BannerEntity> banners) {
        this.banners = banners;
        if (mPresentation != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0
                if (!Settings.canDrawOverlays(this)) {
                    ToastUtil.makeText(mContext, "请授权副屏展示权限", false);
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
                } else {
                    mPresentation.setImages(banners);
                    mPresentation.show();
                }
            } else {
                mPresentation.setImages(banners);
                mPresentation.show();
            }
        }
    }

    private void initUpdateDialog(String updateInfo, String version, boolean isForceUp) {
        final AlertDialog updateDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_update_home).create();

        final RLinearLayout progressLl = updateDialog.getView(R.id.ll_progress);
        rocketProgressView = updateDialog.getView(R.id.progress_rocket);
        final TextView contentTextView = updateDialog.getView(R.id.tv_update_info);
        contentTextView.setText(updateInfo);
        final TextView versionTextView = updateDialog.getView(R.id.tv_version);
        versionTextView.setText("v" + version);
        final RTextView updateBtn = updateDialog.getView(R.id.rtv_update);
        updateDialog.setOnClickListener(R.id.rtv_update, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateAppService.startDownloadService(mContext);
                setViewVisibility(progressLl, true);
                setViewVisibility(updateBtn, false);
            }
        });
        final LinearLayout llCloseDialog = updateDialog.getView(R.id.ll_close_dialog);
        llCloseDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
            }
        });
        if (isForceUp) {
            setViewVisibility(llCloseDialog, false);
        } else {
            setViewVisibility(llCloseDialog, true);
        }
        updateDialog.show();

    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (Settings.canDrawOverlays(this)) {
                if (!ListUtil.isListEmpty(banners) && mPresentation != null) {
                    mPresentation.setImages(banners);
                    mPresentation.show();
                }
            } else {
                PosToast.INSTANCE.makeShortToast(mContext, "请授权副屏展示权限");
                if (!Settings.canDrawOverlays(this)) {
                    //申请绘图权限
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
                }
            }
        }
    }

}
